package utilities
{
	import flash.display.DisplayObjectContainer;
	import flash.text.TextField;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	/**
	 * ...
	 * @author Leong Shi Yun Davina
	 */
	public class Profiler 
	{
		/* private const/var */
		private var m_iCurrTime:int = 0;
		private var m_iPrevTime:int = 0;
		private var m_vTimer:Vector.<int> = null;
		
		private var m_nDt:Number = 0;
		private var m_iFps:int = 0;
		private var m_iTotalFps:int = 0;
		private var m_nAvgFps:Number = 0;
		
		private var m_txt:TextField = null;
		
		public function Profiler(nX:Number, nY:Number, displayObjContainer:DisplayObjectContainer):void
		{
			init(nX, nY, displayObjContainer);
		}
		
		public function init(nX:Number, nY:Number, displayObjContainer:DisplayObjectContainer):void
		{
			if (!m_txt)
			{
				m_txt = new TextField();
				m_txt.x = nX;
				m_txt.y = nY;
				m_txt.width = 160;
				m_txt.height = 65;
				m_txt.border = true;
				
				if (!displayObjContainer.contains(m_txt))
				{
					displayObjContainer.addChild(m_txt);
				}
			}
			
			m_vTimer = new Vector.<int>();
			m_iPrevTime = getTimer();
		}
		
		public function update():void
		{
			m_iTotalFps = 0;
			m_iCurrTime = getTimer();
			m_iFps = 1000 / (m_iCurrTime - m_iPrevTime);
			m_nDt = 1 / m_iFps;
			m_vTimer.push(m_iFps);
			m_iPrevTime = getTimer();
			
			if (m_vTimer.length > 60)
			{
				m_vTimer.shift();
			}
			
			for each(var iFps:int in m_vTimer)
			{
				m_iTotalFps += iFps;
			}
			
			m_nAvgFps = m_iTotalFps / m_vTimer.length;
			
			m_txt.text = "Profiler\ndt: " + m_nDt.toString() + "\nfps: " + m_iFps.toString() + "\navg fps: " + m_nAvgFps.toString();
		}
		
		public function destroy(displayObjContainer:DisplayObjectContainer):void
		{
			var iVecLen:int = m_vTimer.length;
			m_vTimer.splice(0, iVecLen);
			m_vTimer = null;
			
			if (displayObjContainer.contains(m_txt))
			{
				displayObjContainer.removeChild(m_txt);
			}
			displayObjContainer = null;
		}
		
		public function get dt():Number
		{
			return m_nDt;
		}
		
		public function get textfield():TextField
		{
			return m_txt;
		}
		public function set textfield(txt:TextField):void
		{
			m_txt = txt;
		}
	}

}